package com.gsx.Controller;

import com.github.pagehelper.PageInfo;
import com.gsx.entity.Tag;
import com.gsx.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admain")
public class TagController {
    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String pages(@RequestParam(name="page",required = true,defaultValue = "0")int page,
                        @RequestParam(name="size",required = true,defaultValue = "5")int size, Model model){

        List<Tag> tagList=tagService.getAllTag(page, size);
        PageInfo pageInfo=new PageInfo(tagList);
        model.addAttribute("pageInfo",pageInfo);
        return "admain/tags";
    }

    @GetMapping("/tags/input")
    public String input(Model model){
        model.addAttribute("tag",null);
        return "admain/tag-input";
    }

    /*保存标签*/
    @PostMapping("/tags")
    public String post(Tag tag, RedirectAttributes attributes){
        if(tagService.getTagByName(tag.getTag_name())!=null){
            return "admain/tag-input";
        }
        if(tag.getTag_name()==null||tag.getTag_name().equals("")){
            return "admain/tag-input";
        }
        int result=tagService.saveTag(tag);
        if(result==0){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/admain/tags";
    }

    /*修改*/
    @GetMapping("tags/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("tag",tagService.getTag(id));
        return "admain/tag-input";
    }

    @PostMapping("/tags/{id}")
    public String editPost(Tag tag, RedirectAttributes attributes,@PathVariable Long id){
        tag.setTag_id(id);
        if(tagService.getTagByName(tag.getTag_name())!=null){
            return "admain/tag-input";
        }
        if(tag.getTag_name()==null||tag.getTag_name().equals("")){
            return "admain/tag-input";
        }
        int result=tagService.updateTag(tag);
        if(result==0){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/admain/tags";
    }

    /*删除类型*/
    @GetMapping("/tags/{id}/delete")
    public String deleteType(@PathVariable Long id,RedirectAttributes attributes){
        int result=tagService.deleteTag(id);
        if(result==0){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/admain/tags";
    }

}
